package network

import (
	"encoding/json"
	"io"
	"net/http"
	"time"
	"yoga/database"
	"yoga/identify"
)

// 通过微信小程序的逻辑，使用前端请求到的code，向微信服务器进行验证
func WeixinGetTokenHandler(w http.ResponseWriter, r *http.Request) {
	// 通过解析传来的json获取到code的值
	type Code struct {
		Code string `json:"code"`
	}
	var code Code
	err := json.NewDecoder(r.Body).Decode(&code)
	if err != nil {
		http.Error(w, "Invalid JSON format", http.StatusBadRequest)
		return
	}
	if code.Code == "" {
		http.Error(w, "Invalid JSON format", http.StatusBadRequest)
		return
	}
	id, auth, err := identify.IdentifyCode(code.Code)
	if err != nil {
		http.Error(w, "Invalid JSON format", http.StatusBadRequest)
		return
	}
	token, err := identify.GenerateToken(id, auth)
	if err != nil {
		http.Error(w, "Invalid JSON format", http.StatusBadRequest)
		return
	}
	resp := map[string]any{
		"token":   token,                                 // This is a placeholder function for generating a token
		"expires": time.Now().Add(24 * time.Hour).Unix(), // Example token expiration logic
	}
	jsonResp, err := json.Marshal(resp)
	if err != nil {
		http.Error(w, "Failed to generate token", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(jsonResp)
}

// 通过通过传入的account和password进行简单验证
func RequestTokenHandler(w http.ResponseWriter, r *http.Request) {
	type accountAndPassword struct {
		Account  string `json:"account"`
		Password string `json:"password"`
	}
	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Unable to read request body", http.StatusBadRequest)
		return
	}
	var requestData accountAndPassword
	err = json.Unmarshal(body, &requestData)
	if err != nil {
		http.Error(w, "Invalid JSON format", http.StatusBadRequest)
		return
	}
	id, auth, err := database.VerifyAccountAndPasswordGetUserIDAndAuth(requestData.Account, requestData.Password)
	if err != nil {
		http.Error(w, "Invalid account or password", http.StatusUnauthorized)
		return
	}
	token, err := identify.GenerateToken(id, auth)
	if err != nil {
		http.Error(w, "Failed to generate token", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(token))
}
